package org.crown.project.api.wechat;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.crown.common.annotation.EncryptEnable;
import org.crown.common.annotation.NotLogin;
import org.crown.framework.responses.ResponseVo;
import org.crown.project.api.BaseApi;
import org.crown.project.api.module.wechatuser.domain.TbWechatUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author WuFengSheng
 */
@Api(tags = "api登录接口")
@Slf4j
@RestController
@RequestMapping(BaseApi.API_PATH_PREFIX + WeChatApi.API_VERSION + "/weChat")
public class WeChatApi extends BaseApi {

    /**
     * 接口版本
     */
    public static final String API_VERSION = "v1";

    @Autowired
    private WxService wxService;

    /**
     * DYqoyhZq6rssslty5vX54ivLZTptL7VB8yMReK26JFy
     *
     * 将token、timestamp、nonce三个参数进行字典序排序
     * 将三个参数字符串拼接成一个字符串进行sha1加密
     * 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
     *
     * https://www.wufengsheng.top/api/mini/v1/weChat/handleMessage?echostr=wufengsheng
     * 接收微信服务器推送的消息
     * @param signature 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @param echostr   随机字符串
     * @return
     */
    @NotLogin
    @RequestMapping("handleMessage")
    public String handleMessage(HttpServletRequest request, String signature, String msg_signature, String timestamp, String nonce, String echostr){
        log.info("signature={}, msg_signature={}, timestamp={}, nonce={}, echostr={}", signature, msg_signature, timestamp, nonce, echostr);
        boolean isGet = request.getMethod().toLowerCase().equals("get");
        if(isGet){
            return echostr;
        }
        return wxService.acceptMessage(request, msg_signature, timestamp, nonce);
    }

    /**
     * 获取登录凭证（code）
     * 通过凭证进而换取用户登录态信息，包括用户的唯一标识（openid）及本次登录的会话密钥（session_key）
     * @param code
     * @return
     */
    @ApiOperation(value = "微信小程序授权")
    @NotLogin
    @EncryptEnable
    @PostMapping("login")
    public ResponseVo login(@ApiParam("code") @RequestParam("code") String code){
        log.info("code={}", code);
        TbWechatUser tbWechatUser = wxService.weChatMiniLogin(code);
        if(tbWechatUser != null){
            return ResponseVo.success(tbWechatUser);
        }
        return ResponseVo.fail();
    }

    @ApiOperation(value = "微信小程用户信息")
    @EncryptEnable
    @PostMapping("userInfo")
    public ResponseVo userInfo(@RequestParam("encryptedData") String encryptedData, @RequestParam("iv") String iv){
        log.info("encryptedData={}, iv={}",encryptedData, iv);
        Long userId = getUserId();
        if(userId != null){
            TbWechatUser tbWechatUser = wxService.userInfo(userId, encryptedData, iv);
            if(tbWechatUser != null){
                return ResponseVo.success(tbWechatUser);
            }
        }
        return ResponseVo.fail();
    }

    @ApiOperation(value = "微信小程用户手机号")
    @EncryptEnable
    @PostMapping("phoneNumber")
    public ResponseVo phoneNumber(@RequestParam("encryptedData") String encryptedData, @RequestParam("iv") String iv){
        log.info("encryptedData={}, iv={}",encryptedData, iv);
        Long userId = getUserId();
        if(userId != null){
            TbWechatUser tbWechatUser = wxService.phoneNumber(userId, encryptedData, iv);
            if(tbWechatUser != null){
                return ResponseVo.success(tbWechatUser);
            }
        }
        return ResponseVo.fail();
    }

    @ApiOperation(value = "获取当前的地理位置")
    @EncryptEnable
    @PostMapping("getLocation")
    public ResponseVo getLocation(@ApiParam("tbWechatUser") TbWechatUser tbWechatUser){
        log.info("tbWechatUser={}", tbWechatUser);
        if(tbWechatUser != null){
            Long userId = getUserId();
            if(userId != null){
                tbWechatUser = wxService.getLocation(userId, tbWechatUser);
                if(tbWechatUser != null){
                    return ResponseVo.success(tbWechatUser);
                }
            }
        }
        return ResponseVo.fail();
    }

    @ApiOperation(value = "打开地图选择位置")
    @EncryptEnable
    @PostMapping("chooseLocation")
    public ResponseVo chooseLocation(@ApiParam("tbWechatUser") TbWechatUser tbWechatUser){
        log.info("tbWechatUser={}", tbWechatUser);
        if(tbWechatUser != null){
            Long userId = getUserId();
            if(userId != null){
                tbWechatUser = wxService.chooseLocation(userId, tbWechatUser);
                if(tbWechatUser != null){
                    return ResponseVo.success(tbWechatUser);
                }
            }
        }
        return ResponseVo.fail();
    }
}
